/**
 * Project: topdt-jbpm
 * Copyright 2013  Top Digital Technology  Co. Ltd.
 * All right reserved.
 */
package com.topdt.jbpm.service.cmd;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jbpm.api.Execution;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.TaskService;
import org.jbpm.api.task.Participation;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.task.TaskImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.thx.common.spring.BeanFactory;
import com.thx.common.util.AppContext;
import com.thx.common.util.ThreadLocalContext;
//import com.iplanet.services.comm.share.Request;
import com.topdt.jbpm.Constants;
import com.topdt.jbpm.WorkflowException;
import com.topdt.jbpm.form.Document;
import com.topdt.jbpm.form.FormUI;
import com.topdt.jbpm.identity.IdFactory;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.identity.impl.IIdentityServiceFactory;
import com.topdt.jbpm.model.Activity;
import com.topdt.jbpm.model.AppType;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.HistTodo;
import com.topdt.jbpm.model.SendMessage;
import com.topdt.jbpm.model.SendRecord;
import com.topdt.jbpm.model.Todo;
import com.topdt.jbpm.model.Work;
import com.topdt.jbpm.service.AppTypeService;
import com.topdt.jbpm.service.Context;
import com.topdt.jbpm.service.JbpmService;
import com.topdt.jbpm.service.SendMailService;
import com.topdt.jbpm.service.SendRecordService;
import com.topdt.jbpm.service.SendSmsService;

/**
 * 建立日期 : 2013-5-2 下午7:24:21<br>
 * 作者 : balance<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
public class SubmitWorkCmd implements Command<SubmitResult> {

	private String todoId;

	private Document doc;

	private String outCome;

	private Map<String, String> users;

	private Todo todo;

	private TaskImpl task;

	private Map<String, Object> taskVars;

	private Activity activity;

	private Context context;

	private Object nextCircs;

	private JbpmService jbpmService;

	private TaskService taskService;

	private ExecutionService exeService;

	private Map<String, Object> vars;

	private SubmitResult result;

	private Work work;

	private IdentityService idService;

	private boolean free = false;

	public SubmitWorkCmd(String todoId, Document document, String outCome, Map<String, String> users,
			Map<String, Object> vars) {
		this.todoId = todoId;
		this.doc = document;
		this.outCome = outCome;
		this.users = users;// 为后面环节选定的人员
		this.vars = vars;
		this.result = new SubmitResult();
		this.idService = IdFactory.getIdentityServiceFactory().getIdentityService();
	}

	public SubmitResult execute(JbpmService jbpmService) {

		this.jbpmService = jbpmService;

		todo = jbpmService.getTodoDao().get(todoId);

		String workId = todo.getWorkId();
		work = jbpmService.getWorkDao().get(workId);

		String taskId = todo.getTaskId();

		if (taskId == null) {
			free = true;
			exeFree();
		} else
			exeJbpm();

		return result;

	}

	private void exeFree() {
		// --删掉自己的待办
		jbpmService.getTodoDao().delete(todoId);
		/*
		 * 更新待办短信记录表中的状态
		 * wangxufeng add 2014-01-09
		 */
		/*SendRecordService recordService = (SendRecordService)SysContext.getBean(SendRecordService.class);
		recordService.updateType(todoId);*/
		// add over
		/*
		 * modify by calonlan 
		 * 待办完成，相应的提醒记录(如果还没有发送)应该删除
		 * 
		 */
		SendRecordService recordService = (SendRecordService) BeanFactory.getBean("sendRecordService");
		List<SendRecord> records = recordService.findByTodoId(todoId);
		for(SendRecord record : records) {
			record.setStatus("5");
			recordService.update(record);
		}
		HistTodo hTodo = new HistTodo(todo);
		hTodo.setState(Todo.STATE_FINISHED);
		hTodo.setFinishTime(new Date());
		//获取应用类型名称
		String appId = work.getAppId();
		AppTypeService typeService = (AppTypeService) BeanFactory.getBean("appTypeService");
		AppType appType = typeService.getAppTypeByAppId(appId);
		String appTypeName = appType==null?"":appType.getTypeName();
		if (users != null) {
			long batch = System.currentTimeMillis();
			hTodo.setDestActivityName("自由流程：批号[" + batch + "]");
			jbpmService.getHistTodoDao().save(hTodo);

			Set<String> set = this.users.keySet();
			String u = users.get(set.iterator().next());

			String[] us = u.split(",");

			int seq = 1;

			IdentityService identityService = IIdentityServiceFactory.getSingleton().getIdentityService();
			List<User> nUsers = new ArrayList<User>();
			for (String uid : us) {
				Todo todo = new Todo();
				todo.setArriveTime(new Date());
				todo.setFromUserId(this.todo.getToUserId());
				todo.setActivityName("自由流程：批号[" + batch + "]");
				todo.setTodoTitle(work.getWorkTitle());
				todo.setToUserId(uid);
				todo.setWorkId(this.todo.getWorkId());
				todo.setState(Todo.STATE_READY);
				todo.setBatch(batch);
				todo.setTodoMode(this.todo.getTodoMode());
				todo.setSeqNUM(seq++);
				todo.setAppName(this.todo.getAppName());
				todo.setCompanyId(this.todo.getCompanyId());
				todo.setPreActivityName(this.todo.getActivityName());
				jbpmService.getTodoDao().save(todo);
				
				//消息提醒
				// wangxufeng edit 自由流程  只为下一步骤：发送短信和邮件 2014-12-26
				String isSendMail = AppContext.getProperties("isSendMail");
				String isSendSms = AppContext.getProperties("isSendSms");
				String isDelaySendSms = AppContext.getProperties("isDelaySendSms");
				String starterName = jbpmService.findStarterNameByWorkId(this.todo.getWorkId());
				String html = sendTodo(todo);
				SendMessage message = new SendRecord();
				message.setToUserId(todo.getToUserId());
				message.setFromUserId(todo.getFromUserId());
				message.setStarterName(starterName);
				message.setSubject(todo.getTodoTitle());
				message.setContent(html);
				message.setAppTypeName(appTypeName);
				//是否启用邮件提醒
				if ("true".equals(isSendMail)) {
					SendMailService mailService = (SendMailService) BeanFactory.getBean(SendMailService.class);
					mailService.send(message);
				}
				//是否启用短信提醒
				if ("true".equals(isSendSms)) {
					//延迟发送
					if ("true".equals(isDelaySendSms)) {
						/*SendRecordService recordService = 
								(SendRecordService) BeanFactory.getBean(SendRecordService.class);*/
						SendRecord record = new SendRecord();
						record.setCompanyId(AppContext.getCurrentComId());
						record.setContent(html);
						record.setCreateDate(new Timestamp(System.currentTimeMillis()));
						record.setFromUserId(todo.getFromUserId());
						record.setStarterName(starterName);
						record.setSubject(todo.getTodoTitle());
						record.setTodoId(todo.getTodoId());
						record.setToUserId(todo.getToUserId());
						record.setFromUserId(todo.getFromUserId());
						record.setType("sms");
						recordService.save(record);
					//及时发送	
					} else {
						SendSmsService smsService = 
								(SendSmsService) BeanFactory.getBean(SendSmsService.class);
						smsService.send(message);
					}
					
				}
				User user = identityService.getUserById(todo.getToUserId());
				nUsers.add(user);
			}
			Map<String, List<User>> nextActors = new HashMap<String, List<User>>();
			nextActors.put("nUsers", nUsers);
			result.setNextActors(nextActors);
			result.setType(SubmitResult.TYPE_FREE);
			result.setMessage("工作已提交到" + result.spellNextMsgForFree() + "!");
			work.setCurActivityName("[自由流程:流转中]");
			work.setWorkState(Work.STATE_RUN);
			jbpmService.getWorkDao().update(work);
		} else {
			List<Todo> todos = jbpmService.getTodoDao().getTodosByWorkId(work.getWorkId());
			if (todos != null && todos.size() > 0) {
				hTodo.setDestActivityName("自由流程：本人结束");
				jbpmService.getHistTodoDao().save(hTodo);
				IdentityService identityService = IIdentityServiceFactory.getSingleton().getIdentityService();
				List<User> nUsers = new ArrayList<User>();
				for (Todo nTodo : todos) {
					User user = identityService.getUserById(nTodo.getToUserId());
					nUsers.add(user);
				}
				Map<String, List<User>> nextActors = new HashMap<String, List<User>>();
				nextActors.put("nUsers", nUsers);
				result.setNextActors(nextActors);
				result.setType(SubmitResult.TYPE_FREE);
				result.setMessage("您的任务已结束，本工作还有" + result.spellNextMsgForFree() + "在处理！");

			} else {
				hTodo.setDestActivityName("自由流程：结束");
				jbpmService.getHistTodoDao().save(hTodo);
				result.setType(SubmitResult.TYPE_FREE_END);
				result.setMessage("工作已结束！");
				work.setWorkState(Work.STATE_END);
				work.setCurActivityName("[自由流程：结束]");
				jbpmService.getWorkDao().update(work);
				/*LogInfo info = new LogInfo(hTodo.getToUser(), Constants.WORKFLOW_MODULE, Constants.ADD, String.format(
						Constants.WORKDESC, work.getStarterName(), work.getWorkTitle()), new Date(), "");
				ThreadLocalContext.set(Constants.LOGINFO_KEY, info);*/
			}

		}

	}

	/**
	 * 
	 * <b>Method sendTodo</b>
	 * <dd>方法作用：(根据todo将要发送的内容封装完整)
	 * 
	 * @author Wangxufeng 抽取出来的公共部分作为一个方法
	 * @param todo
	 * @return
	 * @since Met 1.0
	 */
	private String sendTodo(Todo todo) {
		FormUI ui = jbpmService.getWorkForm(todo.getTodoId(), false);
		org.jsoup.nodes.Document doc = Jsoup.parse(ui.getUiText(), "UTF-8");
		Elements handles = doc.getElementsByClass("handle");
		handles.html("");
		Element div_dialog = doc.getElementById("dialog");
		div_dialog.remove();
		String oaAppName = AppContext.getProperties("oaAppName");
		oaAppName = "/" + oaAppName;
		String oaStaticAdd = AppContext.getProperties("oaStaticAdd");
		String html = doc.outerHtml().replaceAll(oaAppName, oaStaticAdd);
		return html;
	}

	/**
	 * 
	 * <b>Method remindByCondition</b>
	 * <dd>方法作用：(根据条件判断做出不同的提醒)
	 * 
	 * @param todo
	 * @param workId
	 * @param starterName
	 * @param html
	 * @author Wangxufeng add 2014-11-19
	 * @since Met 1.0
	 */
	private void remindByCondition(Todo todo, char[] remaindChar,String starterName, String html) {
		/*
		 * 下一步骤 发起人 全部经办人 1 1 1 0 0 0 0 0 0 事物 短信 邮件
		 */
		String isEnableMail = AppContext.getProperties("isSendMail");
		String isEnableSms = AppContext.getProperties("isSendSms");
		String isDelaySendSms = AppContext.getProperties("isDelaySendSms");
		String appId = work.getAppId();
		AppTypeService typeService = (AppTypeService) BeanFactory.getBean("appTypeService");
		AppType appType = typeService.getAppTypeByAppId(appId);
		String appTypeName = appType==null?"":appType.getTypeName();
		SendMessage message = new SendRecord();
		message.setToUserId(work.getStarter());
		message.setFromUserId(todo.getFromUserId());
		message.setStarterName(starterName);
		message.setSubject(todo.getTodoTitle());
		message.setContent(html);
		message.setAppTypeName(appTypeName);
		if (remaindChar != null) {
			List<HistTodo> histTodos = 
					jbpmService.getHistTodoDao().findWorkRecordFromHistTodo(todo.getWorkId());
			SendMessage[] messages = {};
			if (histTodos.size() > 0) {
				for (int i=0; i<histTodos.size(); i++) {
					messages = new SendRecord[histTodos.size()];
					message.setToUserId(histTodos.get(i).getToUser());
					messages[i] = message;
				}
			}
				
			//邮件提醒
			if("true".equals(isEnableMail)) {
				SendMailService mailService = 
						(SendMailService) BeanFactory.getBean(SendMailService.class);
				//发起人发送邮件提醒
				if (Character.toString(remaindChar[3]).equals(Constants.IS_SEND)) {
					
					mailService.send(message);
				}
				//全部经办人发送邮件提醒
				if (Character.toString(remaindChar[5]).equals(Constants.IS_SEND)) {
					mailService.send(messages);
				}
				
				
			}
			//短信提醒
			if ("true".equals(isEnableSms)) {
				//延迟发送
				if ("true".equals(isDelaySendSms)) {
					SendRecordService recordService = 
							(SendRecordService) BeanFactory.getBean(SendRecordService.class);
					//发起人发送短信提醒
					if (Character.toString(remaindChar[2]).equals(Constants.IS_SEND)) {
						SendRecord record = new SendRecord();
						record.setCompanyId(AppContext.getCurrentComId());
						record.setContent(html);
						record.setCreateDate(new Timestamp(System.currentTimeMillis()));
						record.setFromUserId(todo.getFromUserId());
						record.setStarterName(starterName);
						record.setSubject(todo.getTodoTitle());
						record.setTodoId(todo.getTodoId());
						record.setToUserId(todo.getToUserId());
						record.setFromUserId(todo.getFromUserId());
						record.setType("sms");
						recordService.save(record);
					}
					
					//全部经办人发送短信提醒
					if (Character.toString(remaindChar[4]).equals(Constants.IS_SEND)) {
						SendRecord record;
						if (histTodos.size() > 0) {
							record = new SendRecord();
							record.setCompanyId(AppContext.getCurrentComId());
							record.setContent(html);
							record.setCreateDate(new Timestamp(System.currentTimeMillis()));
							record.setFromUserId(todo.getFromUserId());
							record.setStarterName(starterName);
							record.setSubject(todo.getTodoTitle());
							record.setTodoId(todo.getTodoId());
							record.setToUserId(todo.getToUserId());
							record.setFromUserId(todo.getFromUserId());
							record.setType("sms");
							for (int i=0; i<histTodos.size(); i++) {
								record.setToUserId(histTodos.get(i).getToUser());
								recordService.save(record);
							}
							
						}		
					}
					
					
				//及时发送	
				} else {
					SendSmsService smsService = 
							(SendSmsService) BeanFactory.getBean(SendSmsService.class);
					//发起人发送短信提醒
					if (Character.toString(remaindChar[2]).equals(Constants.IS_SEND)) {
						if ("true".equals(isDelaySendSms)) {
							
						}
						smsService.send(message);
					}
					
					//全部经办人发送短信提醒
					if (Character.toString(remaindChar[4]).equals(Constants.IS_SEND)) {
						smsService.send(messages);
					}
				}
				
			}

		}
	}
	/**
	 * @author Wangxufeng
	 * @date 2014-12-25
	 * 公共的通过todo得到提醒方式
	 */
	private char[] getRemind(Todo todo) {
		String activityName = todo.getActivityName();
		String flowId = work.getFlowId();
		String appId = work.getAppId();
		String formId = jbpmService.getAppDao().getById(appId).getForm().getFormId();
		Object[] objs = new Object[] { appId, flowId, activityName, formId };
		Control control = jbpmService.getControlDao().getControlByObjects(objs);
		String remindControl = control.getRemindControl();
		if(remindControl != null){
			return remindControl.toCharArray();
		}
		return null;
	}

	private void exeJbpm() {
		taskService = jbpmService.getTaskService();

		exeService = jbpmService.getExecutionService();

		task = (TaskImpl) taskService.getTask(todo.getTaskId());

		context = (Context) jbpmService.getTaskService().getVariable(todo.getTaskId(), Context.KEY);

		context.setCurrentActor(todo.getToUserId());

		context.setAppName(todo.getAppName());

		taskVars = new HashMap<String, Object>();
		taskVars.put(Context.KEY, context);
		if (this.vars != null)
			taskVars.putAll(vars);

		preActorsForDownTask();

		ThreadLocalContext.set("_currentActor", todo.getToUserId());// 当前提交任务放入现成环境中

		completeTask();

	}

	private void completeTask() {
		String activityName = task.getActivityName();

		String flowId = context.getFlowId();

		activity = jbpmService.getActivityDao().getActivityById(flowId, activityName);

		Map<String, List<User>> historyUsers = context.getHistoryUsers();
		List<User> actors = null;
		if (historyUsers != null)
			actors = historyUsers.get(activityName + todo.getBatch());

		// 这里要分情况提交任务，1、正常任务（jbpm4.4支持的），2、子任务，3、最后子任务，4、代理人任务......

		if (actors == null || actors.size() <= 1) {// 当前活动属于“单处理人”,actors为null表示是第一个环节
			doSingle();
		} else {// 当前活动属于“多处理人”
			String doRule = activity.getDoRule();
			if (doRule.equals(Activity.DO_UNIQUE))// “多处理人”中的“唯一”
				doUnique();
			else if (doRule.equals(Activity.DO_SEQUENCE))// “多处理人”中的“顺序”
				doSequence();
			else if (doRule.equals(Activity.DO_CONCURRENCE))// “多处理人”中的“并行”
				doConcurrence();
			// TODO 还有其他情况在此后面增加......
		}

		String submitResult = result.getType();

		if (submitResult != null && submitResult.equals(SubmitResult.TYPE_ERROR)) {
			throw new WorkflowException(result.getMessage());
		} else {
			jbpmService.getTodoDao().delete(todoId);// TODO 删除todo变量
			/*
			 * 更新待办短信记录表中的状态
			 * wangxufeng add 2014-01-09
			 */
			/*SendRecordService recordService = (SendRecordService)SysContext.getBean(SendRecordService.class);
			recordService.updateType(todoId);*/
			// add over
			/*
			 * modify by calonlan
			 * 待办完成，相应的提醒记录(如果还没有发送)应该删除
			 */
			SendRecordService recordService = (SendRecordService) BeanFactory.getBean("sendRecordService");
			List<SendRecord> records = recordService.findByTodoId(todoId);
			for(SendRecord record : records) {
				record.setStatus("5");
				recordService.update(record);
			}
			
			HistTodo hTodo = new HistTodo(todo);
			hTodo.setState(Todo.STATE_FINISHED);
			hTodo.setFinishTime(new Date());

			if (nextCircs != null && (nextCircs instanceof Map)) {

				String dest = "";
				Set<String> destActivities = ((Map) nextCircs).keySet();
				for (String act : destActivities) {
					dest = dest + act + ",";
				}

				if (dest.endsWith(","))
					dest = dest.substring(0, dest.length() - 1);
				hTodo.setDestActivityName(dest);
			} else if (result.isEnd()) {
				/*LogInfo info = new LogInfo(hTodo.getToUser(), Constants.WORKFLOW_MODULE, Constants.ADD, String.format(
						Constants.WORKDESC, work.getStarterName(), work.getWorkTitle()), new Date(), "");
				ThreadLocalContext.set(Constants.LOGINFO_KEY, info);*/
				hTodo.setDestActivityName("结束");
			}

			jbpmService.getHistTodoDao().save(hTodo);
		}
	}

	// 将后面活动的处理人放入变量里
	private void preActorsForDownTask() {
		if (users != null) {
			Set<String> keys = users.keySet();
			for (String key : keys) {
				String assginee = (String) taskService.getVariable(task.getId(), key + "_assginee");
				if (assginee == null) {
					taskVars.put(key + "_assginee", users.get(key));
				}
			}
		}
	}

	
	/*
	 * 单人处理任务
	 */
	private void doSingle() {
		taskService.completeTask(task.getId(), outCome, taskVars);
		getNextCircs();
	}

	/*
	 * 多人唯一处理
	 */
	private void doUnique() {

		// 和单人处理没区别
		doSingle();
		// taskService.completeTask(task.getId(), outCome, taskVars);
	}
	/*
	 * 多人并行处理任务
	 */
	private void doConcurrence() {

		String taskId = task.getId();

		TaskImpl superTask = task.getSuperTask();

		List<Task> subTasks = taskService.getSubTasks(superTask.getId());

		// TODO:扩展处，定义任务结束条件，如：一票否决、一票通过、半数以上否决、半数以上通过......
		boolean ending = false;

		if (subTasks.size() == 1 || ending) {// 最后一个子任务，或者满足结束条件

			// TODO:扩展处，定义任务出口，如：由投票结果决定出口路径
			// outCome = "";

			taskService.completeTask(taskId);
			taskService.completeTask(superTask.getId(), outCome, taskVars);
			getNextCircs();
		} else {
			taskService.completeTask(taskId);
			List<User> actors = context.getHistoryUsers().get(this.todo.getActivityName() + todo.getBatch());
			String message = "任务已提交，本环节还有[%s]的任务没有处理！";
			String handlerNames = "";
			for (User user : actors) {
				if (!user.getId().equals(context.getCurrentActor())) {
					Todo todo = jbpmService.findTodoByWorkAndUser(this.todo.getWorkId(), user.getId());
					if (todo != null) {
						if (!"".equals(handlerNames))
							handlerNames += "、";
						handlerNames += idService.getUserById(user.getId()).getName();
					}
				}
			}
			message = String.format(message, handlerNames);
			result.setMessage(message);
			result.setType(result.TYPE_PAUSE_CONCURRENCE);
		}

		taskService.addTaskComment(superTask.getId(), "concurrenceUser:" + this.todo.getToUserId());

	}

	
	/**
	 * 多人顺序处理任务
	 */
	private void doSequence() {
		String taskId = task.getId();
		TaskImpl superTask = task.getSuperTask();
		Integer seq = task.getProgress();// TODO:利用jbpm的progress字段来满足序号

		String appId = work.getAppId();
		AppTypeService typeService = (AppTypeService) BeanFactory.getBean("appTypeService");
		AppType appType = typeService.getAppTypeByAppId(appId);
		String appTypeName = appType==null?"":appType.getTypeName();
		
		List<Task> subTasks = taskService.getSubTasks(superTask.getId());

		if (subTasks.size() == 1) {// 说明是最后一个子任务

			// subTasks.get(0).getId()==taskId 是 true

			taskService.completeTask(taskId);
			taskService.completeTask(superTask.getId(), outCome, taskVars);
			getNextCircs();
		} else {
			String starterName = null;
			String html = null;
			boolean isSendSms = false;
			boolean isSendEmail = false;
			char[] remindChar = getRemind(todo);
			if(remindChar != null){
				if (Character.toString(remindChar[0]).equals(Constants.IS_SEND)) {
					isSendSms = true;
				}
				if (Character.toString(remindChar[1]).equals(Constants.IS_SEND)) {
					isSendEmail = true;
				}
			}
			for (Task subTask : subTasks) {
				Integer nextSeq = subTask.getProgress();
				if (nextSeq == seq + 1) {// 是下一个要执行的任务
					Participation participation = taskService.getTaskParticipations(subTask.getId()).get(0);
					String assignee = participation.getUserId();
					String type = participation.getType();

					subTask.setAssignee(assignee);
					jbpmService.getHistoryService();

					taskService.completeTask(taskId);

					// TODO 扩展待办数据，发送短信提醒等等
					Todo todo = new Todo();
					todo.setArriveTime(new Date());
					todo.setFromUserId(this.todo.getFromUserId());
					todo.setActivityName(this.todo.getActivityName());
					todo.setTaskId(subTask.getId());
					todo.setTodoTitle(this.todo.getTodoTitle());
					todo.setToUserId(assignee);
					todo.setWorkId(this.todo.getWorkId());
					todo.setState(Todo.STATE_READY);
					todo.setBatch(this.todo.getBatch());
					todo.setTodoMode(this.todo.getTodoMode());
					todo.setSeqNUM(this.todo.getSeqNUM() + 1);
					todo.setAppName(this.todo.getAppName());
					todo.setCompanyId(this.todo.getCompanyId());
					todo.setPreActivityName(work.getCurActivityName());
					jbpmService.getTodoDao().save(todo);
					
					
					// wangxufeng edit 默认 只给下一步骤处理人(并且在应用定制中配置要发送的)发送 2014-12-25
					String isEnableMail = AppContext.getProperties("isSendMail");
					String isEnableSms = AppContext.getProperties("isSendSms");
					String isDelaySendSms = AppContext.getProperties("isDelaySendSms");
					starterName = jbpmService.findStarterNameByWorkId(this.todo.getWorkId());
					html = sendTodo(todo);
					SendMessage message = new SendRecord();
					message.setToUserId(todo.getToUserId());
					message.setFromUserId(todo.getFromUserId());
					message.setStarterName(starterName);
					message.setSubject(todo.getTodoTitle());
					message.setContent(html);
					message.setAppTypeName(appTypeName);
					//发送邮件提醒
					if ("true".equals(isEnableMail) && isSendEmail) {
						SendMailService mailService = (SendMailService) BeanFactory.getBean(SendMailService.class);
						mailService.send(message);
					}
					
					//发送短信提醒
					if ("true".equals(isEnableSms) && isSendSms) {
						//延迟发送
						if ("true".equals(isDelaySendSms)) {
							SendRecordService recordService = 
									(SendRecordService) BeanFactory.getBean(SendRecordService.class);
							SendRecord record = new SendRecord();
							record.setCompanyId(AppContext.getCurrentComId());
							record.setContent(html);
							record.setCreateDate(new Timestamp(System.currentTimeMillis()));
							record.setFromUserId(todo.getFromUserId());
							record.setStarterName(starterName);
							record.setSubject(todo.getTodoTitle());
							record.setTodoId(todo.getTodoId());
							record.setToUserId(todo.getToUserId());
							record.setFromUserId(todo.getFromUserId());
							record.setType("sms");
							recordService.save(record);
						//及时发送	
						} else {
							SendSmsService smsService = 
									(SendSmsService) BeanFactory.getBean(SendSmsService.class);
							smsService.send(message);
						}
					}
					// wangxufeng edit over
					result.setType(result.TYPE_PAUSE_CONCURRENCE);
					result.setNextActor(assignee);

					break;
				}
			}
			// wangxufeng add
			if (starterName != null && html != null) {
				Todo tempTodo = new Todo();
				tempTodo.setFromUserId(this.todo.getToUserId());
				tempTodo.setActivityName(this.todo.getActivityName());
				tempTodo.setTodoTitle(this.todo.getTodoTitle());
				tempTodo.setWorkId(this.todo.getWorkId());
				remindByCondition(tempTodo, remindChar, starterName, html);
			}
		}
		taskService.addTaskComment(superTask.getId(), "seqUser:" + this.todo.getToUserId());
	}

	private void getNextCircs() {
		nextCircs = ThreadLocalContext.get("next_circs");
		if (nextCircs != null) {
			ThreadLocalContext.remove("next_circs");
			if (nextCircs instanceof String) {
				String next = (String) nextCircs;
				if (next.equals(Work.STATE_END))
					result.setType(SubmitResult.TYPE_END);
			} else {
				Map<String, List<User>> actors = (Map<String, List<User>>) nextCircs;
				if (actors != null && actors.keySet().size() > 0
						&& actors.get(actors.keySet().iterator().next()) != null) {
					result.setType(SubmitResult.TYPE_NEXT);
					result.setNextActors(actors);
					// --进入下一个环节
					work.setWorkState(Work.STATE_RUN);
					setCurActivityName(actors);
					jbpmService.getWorkDao().update(work);
				} else {
					result.setType(SubmitResult.TYPE_ERROR);
					result.setMessage("没有找到下一环节的处理人。");
				}
			}

		} else {// next_circs为null 本环节结束，但没有进入下一环节，说明下一环节是汇聚节点，还有其他分支没有结束
			result.setType(SubmitResult.TYPE_WAITING_MULTIout);
			clearCurBranchInfo();
		}
	}

	private void setCurActivityName(Map<String, List<User>> actors) {
		String curActivityName = work.getCurActivityName();

		String now = "";
		for (String key : actors.keySet()) {
			now += "[" + key + ":";
			for (User user : actors.get(key)) {
				now += idService.getUserById(user.getId()).getName() + ",";
			}
			now = now.substring(0, now.length() - 1);
			now += "]";
		}

		if (curActivityName == null || curActivityName.trim().length() == 0) {
			curActivityName = now;
			// curActivityName=now.replaceAll("\\]\\[","]\n[");//zhangyong
			// 20141203先注释了
		} else {
			if (curActivityName.matches("^\\[\\d{1}-.*\\]$") && now.matches("^\\[\\d{1}-[^\\[\\]]*\\]$")) {// 说明是多路径情况
				String n = now.substring(1, 2);
				curActivityName = curActivityName.replaceFirst("\\[" + n + "-[^\\[\\]]*\\]", now);
			} else {
				curActivityName = now;
				// curActivityName=now.replaceAll("\\]\\[","]\n[");//zhangyong
				// 20141203先注释了
			}
		}

		work.setCurActivityName(curActivityName);
	}

	private void clearCurBranchInfo() {
		String exeId = task.getExecutionId();
		if (exeId == null) {
			TaskImpl superTask = task.getSuperTask();
			if (superTask != null)
				exeId = superTask.getExecutionId();
		}

		if (exeId != null) {
			Execution exe = exeService.findExecutionById(exeId);
			String branch = exe.getName();
			String curActivityName = work.getCurActivityName();
			if (branch != null && curActivityName.matches("^\\[\\d{1}-.*\\]$")) {// 说明是多路径情况
				curActivityName = curActivityName.replaceFirst("\\[" + branch + "-[^\\[\\]]*\\]", "");
				work.setCurActivityName(curActivityName);
				jbpmService.getWorkDao().update(work);
			}
		}
	}
}
